﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
using Telerik.Windows.Controls;
using System.Diagnostics.Contracts;
using System.Windows.Input;

namespace MoneyManager.GUI
{
    /// <summary>
    /// Interaction logic for AddEditTransaction.xaml
    /// </summary>
    public partial class AddEditTransaction : UserControl, INotifyPropertyChanged
    {
        private Transaction _currentTransaction;
        private Transaction _backupTransaction;
        public Transaction CurrentTransaction 
        { 
            get
            {
                return _currentTransaction;
            }
            set 
            {
                if (value == null)
                {
                    ClearAll();
                    return;
                }
                ApplyButton.Focus();
                if (!SavedChanges())
                    return;
                _backupTransaction = value;
                _currentTransaction = (Transaction)_backupTransaction.Clone();
                    
                OnPropertyChanged("CurrentTransaction");
                UpdateIERadioButtons();
                CategoryCombobox.SelectedItem = CurrentTransaction.Category;
            }
        }

        public Boolean IsEditing
        {
            get
            {
                return _backupTransaction != null;
            }
        } //while making new transaction field _backupTransaction not setted

        public ObservableCollection<Category> Categories
        {
            get;
            private set;
        }

        public AddEditTransaction()
        {
            StyleManager.ApplicationTheme = new Expression_DarkTheme();
            Categories = new ObservableCollection<Category>();

            InitializeComponent();
        }
        
        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string propertyname)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
        }

        #endregion

        #region Event handlers

        private void NewToggleButton_Click(object sender, RoutedEventArgs e)
        {
            if (!SavedChanges())
                return;
            _currentTransaction = new Transaction();
            _backupTransaction = null;
            OnPropertyChanged("CurrentTransaction");
            ClearAll();
            IE_Checked();
            CategoryCombobox.SelectedIndex = 0;
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            if (IsEditing)
                TransactionManager.Remove(_backupTransaction);

            CurrentTransaction = new Transaction();
            ClearAll();
        }

        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            ApplyChanges();
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            if (!IsEditing)
            {
                ClearAll();
            }
            else CurrentTransaction = _backupTransaction;
        }

        private void ClearAll()
        {
            UpdateIERadioButtons();   
            CategoryCombobox.SelectedItem = null;
            DescriptionTextBox.Text = "";
            AmountTextBox.Text = "";
         //   DatePicker.SelectedValue = null;
            NotesTextBox.Text = null;
        }

        private void IE_Checked(object sender = null, RoutedEventArgs e = null) 
        {
            CategoryType type = IncomeRadioButton.IsChecked ?? false ? CategoryType.Income : CategoryType.Expense;
            var categories = CategoryManager.Categories.Where(c => (c.Type == type || c.Type == CategoryType.Both)).OrderBy(c=>c.Name).ToList();
            Categories.Clear();
            foreach (var cat in categories)
                Categories.Add(cat);
            CategoryCombobox.SelectedIndex = 0;
            CurrentTransaction.Type = IncomeRadioButton.IsChecked ?? false ? TransactionType.Income : TransactionType.Expense;
        }

        #endregion

        private void UpdateIERadioButtons()
        {
            if (CurrentTransaction != null)
            {
                IncomeRadioButton.IsChecked = (CurrentTransaction.Type == TransactionType.Income);
                ExpenseRadioButton.IsChecked = (CurrentTransaction.Type == TransactionType.Expense);
            }
            else IncomeRadioButton.IsChecked = ExpenseRadioButton.IsChecked = false;
        }

        private void ApplyChanges()
        {
            CurrentTransaction.Type = (IncomeRadioButton.IsChecked ?? false) ? TransactionType.Income : TransactionType.Expense;
            CurrentTransaction.Category = (Category)CategoryCombobox.SelectedValue;

            if (!CurrentTransaction.Validate()) return;

            if (!IsEditing) // new transaction
            {
                TransactionManager.Add(CurrentTransaction);
                _backupTransaction = _currentTransaction;
            }
            else // editing transaction
            {
                _backupTransaction.CopyFields(CurrentTransaction);
                DBManager.Update(_backupTransaction);
            }
            TransactionUserControl.TransactionsView.Refresh();
        }

        private bool SavedChanges()
        {
            if (CurrentTransaction == null)
                return true;
            Transaction original = IsEditing ? _backupTransaction : new Transaction();
            if (!original.Equals(_currentTransaction))
            {
                var res = MessageBox.Show("Save changes in current transaction?", "Save changes", MessageBoxButton.YesNoCancel);
                switch (res)
                {
                    case MessageBoxResult.Yes:
                        ApplyChanges();
                        return true;
                    case MessageBoxResult.No:
                        return true;
                    case MessageBoxResult.Cancel:
                        return false;
                }
            }
            return true;
        }
   }
}
